﻿using System;

namespace ServerFramework.Tools
{
    /// <summary>
    /// guid tool
    /// </summary>
    public class GUIDTool
    {
        private static object _flaglock = new object();
        private static UInt16 Temp = 0;
        /// <summary>
        /// 只在不同服务器中唯一 不确保所有唯一  serverid 必须保证为非负数
        /// </summary>
        /// <param name="serverid"></param>
        /// <returns></returns>
        public static long GenerateGUID(Int16 serverid)
        {
            lock(_flaglock)
            {
                Temp++;
                ulong uid = 0;
                uint front = ((uint)(((ushort)(Temp)) | ((uint)((ushort)(serverid))) << 16));
                uint time = (uint)(DateTime.Now.Ticks / 10000);
                uid = (ulong)(time | (ulong)(front) << 32);
                return (long)uid;
            }
        }

        /// <summary>
        /// 只在真个进程中为一
        /// </summary>
        /// <returns></returns>
        public static long GenerateGUID()
        {
            lock (_flaglock)
            {
                Temp++;
                ulong uid = 0;
                uint front = ((uint)(((ushort)(Temp)) | ((uint)((ushort)(Int16.MaxValue))) << 16));
                uint time = (uint)(DateTime.Now.Ticks / 10000);
                uid = (ulong)(time | (ulong)(front) << 32);
                return (long)uid;
            }
        }

        public static int GenerateID(int a, int b)
        {
            int temp = a << 16;
            return temp + b;
        }

        public static long GenerateID(uint a, uint b)
        {
            ulong temp = 0;
            temp = (ulong)(b | (ulong)(a) << 32);
            return (long)temp;
        }

        public static int StringCat(params object[] args)
        {
            string str = "";
            for (int i = 0; i < args.Length; ++i)
            {
                str += args[i].ToString();
            }
            int ret = 0;
            int.TryParse(str, out ret);
            return ret;
        }

        public static long StringCatId(params object [] args)
        {
            string str = "";
            for (int i = 0; i < args.Length; ++i)
            {
                str += args[i].ToString();
            }
            long ret = 0;
            long.TryParse(str, out ret);
            return ret;
        }

        private static int m_linkId = 10;
        public static int LinkId
        {
            get
            {
                if (m_linkId < 10) { m_linkId = 10; }
                return m_linkId++;
            }
        }
    }
}
